//
//  OrderDetailViewController.m
//  B2C
//
//  Created by 李小龙 on 2017/8/2.
//  Copyright © 2017年 lixiaolong. All rights reserved.
//

#import "OrderDetailViewController.h"
#import "OrderDetailTableViewCell.h"
#import "RefundViewController.h"
#import "ReportViewController.h"
#import "OrderHalfButton.h"
#import "LogisticsViewController.h"
#import "EvaluateViewController.h"
#import "LogisticsWebViewController.h"
#import "PayStatusViewController.h"
#import "PayView.h"
//#import "GoodEvaluateListViewController.h"
//#import "EditPriceViewController.h"
//#import "EditSendViewController.h"
#import "OthersMemberInfoModel.h"
//#import "OthersStoreViewController.h"
#import "GoodsDetailViewController.h"
#import <AlipaySDK/AlipaySDK.h>

@interface OrderDetailViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UIButton *bottomButton;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomHLayout;
@property (nonatomic, strong) PayView *payView;

@end

@implementation OrderDetailViewController
#pragma mark - Get
- (PayView *)payView {
    if (!_payView) {
        _payView = [[PayView alloc] initWithFrame:Screen];
    }
    return _payView;
}
#pragma mark - IBAction
- (IBAction)bottomServiceButtonAction:(id)sender {
    NSLog(@"联系客服");
    [self goToServiceChat];
    /*
    if ([self.detailModel.shop.sid isEqualToString:@"0"]) {
        // 自营
        [self getCustomerInfo:self.detailModel];
    } else {
        // 个人、企业
        [self contactBuyer:self.detailModel];
    }
     */
}
#pragma mark - ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"订单详情";
    [self.tableView clearExtendCellLine];
    [self getNetData];
}
- (void)disMissSelf {
    switch (self.fromType) {
        case FromTypeStatus:
        {
            [self popToRootViewController];
        } break;
        case FromTypeSelfOrder: case FromTypeMineStore:
        {
            [super disMissSelf];
        } break;
        default:
            break;
    }
}
#pragma mark - 网络请求
- (void)getNetData {
    NSString *orderUrl;
    if (self.fromType == FromTypeMineStore) {
        orderUrl = URL_Get_Shop_Order_Detail;
    } else {
        orderUrl = URL_Get_Order_Detail;
    }
    // 根据订单id获取订单详细信息
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:orderUrl parameters:@{@"omid":self.detailModel.omid} success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            self.detailModel = [OrderModel mj_objectWithKeyValues:responseObject[@"data"]];
            [self.tableView reloadData];
            switch (self.fromType) {
                case FromTypeSelfOrder: case FromTypeStatus:
                {
                    [self createBottomView];
                } break;
                case FromTypeMineStore:
                {
                    self.bottomHLayout.constant = 0;
                    [self.view layoutIfNeeded];
                    [self.bottomView setHidden:YES];
                } break;
                default:
                    break;
            }
        } else {
            [MBProgressHUD showError:self.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showError:self.view title:@"" code:@"" animated:YES];
    }];
}
#pragma mark - action
- (void)removeFourthBackViewSubView {
    for (UIView *view in self.bottomView.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            if (view.tag != 10000) {
                [view removeFromSuperview];
            } else {
                NSLog(@"%@",view);
            }
        }
    }
}
- (void)createBottomView {
    // 状态0已提交，1已付款，2已发货，3已签收，4已评价，5已取消，6已删除，7退款申请，8已退款
    CGFloat buttonY = 9;
    CGFloat buttonW = 75;
    CGFloat kong = 5;
    [self removeFourthBackViewSubView];
    switch (self.detailModel.omstatus.intValue) {
        case 0:
        {
            for (NSInteger i = 1; i <= 2; i++) {
                CGRect frame = CGRectMake(ScreenWidth-(kong+buttonW)*i, buttonY, buttonW, self.bottomView.height-buttonY*2);// self.fourthBackView.width
                
                OrderButtonType type;
                NSString *buttonTitle;
                UIColor *color, *borderColor;
                if (i == 1) {
                    type = OrderButtonTypePay;
                    buttonTitle = @"付款";
                    color = [UIColor ThemeColor];
                    borderColor = [UIColor ThemeColor];
                } else {
                    type = OrderButtonTypeCancel;
                    buttonTitle = @"取消订单";
                    color = [UIColor blackTextColor];
                    borderColor = [UIColor grayTextColor];
                }
                
                OrderHalfButton *button = [OrderHalfButton orderButtonWithType:type frame:frame buttonTitle:buttonTitle color:color borderColor:borderColor];
                [button addTarget:self action:@selector(orderButtonAction:) forControlEvents:UIControlEventTouchUpInside];
                [self.bottomView addSubview:button];
                
            }
        } break;
        case 1:
        {
            OrderHalfButton *button = [OrderHalfButton orderButtonWithType:OrderButtonTypeAlert frame:CGRectMake(ScreenWidth-(kong+buttonW), buttonY, buttonW, self.bottomView.height-buttonY*2) buttonTitle:@"提醒发货" color:[UIColor ThemeColor] borderColor:[UIColor ThemeColor]];
            [button addTarget:self action:@selector(orderButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            [self.bottomView addSubview:button];
        } break;
        case 2:
        {
            for (NSInteger i = 1; i <= 2; i++) {
                CGRect frame = CGRectMake(ScreenWidth-(kong+buttonW)*i, buttonY, buttonW, self.bottomView.height-buttonY*2);// self.fourthBackView.width
                
                OrderButtonType type;
                NSString *buttonTitle;
                UIColor *color, *borderColor;
                if (i == 1) {
                    type = OrderButtonTypeSure;
                    buttonTitle = @"确认收货";
                    color = [UIColor ThemeColor];
                    borderColor = [UIColor ThemeColor];
                } else {
                    type = OrderButtonTypeCheck;
                    buttonTitle = @"查看物流";
                    color = [UIColor blackTextColor];
                    borderColor = [UIColor grayTextColor];
                }
                
                OrderHalfButton *button = [OrderHalfButton orderButtonWithType:type frame:frame buttonTitle:buttonTitle color:color borderColor:borderColor];
                [button addTarget:self action:@selector(orderButtonAction:) forControlEvents:UIControlEventTouchUpInside];
                [self.bottomView addSubview:button];
                
            }
        } break;
        case 3:
        {
            for (NSInteger i = 1; i <= 3; i++) {
                CGRect frame = CGRectMake(ScreenWidth-(kong+buttonW)*i, buttonY, buttonW, self.bottomView.height-buttonY*2);// self.fourthBackView.width
                
                OrderButtonType type;
                NSString *buttonTitle;
                UIColor *color, *borderColor;
                if (i == 1) {
                    type = OrderButtonTypeEvaluate;
                    buttonTitle = @"评价";
                    color = [UIColor ThemeColor];
                    borderColor = [UIColor ThemeColor];
                } else if (i == 2) {
                    type = OrderButtonTypeDelete;
                    buttonTitle = @"删除订单";
                    color = [UIColor blackTextColor];
                    borderColor = [UIColor grayTextColor];
                } else {
                    type = OrderButtonTypeCheck;
                    buttonTitle = @"查看物流";
                    color = [UIColor blackTextColor];
                    borderColor = [UIColor grayTextColor];
                }
                
                OrderHalfButton *button = [OrderHalfButton orderButtonWithType:type frame:frame buttonTitle:buttonTitle color:color borderColor:borderColor];
                [button addTarget:self action:@selector(orderButtonAction:) forControlEvents:UIControlEventTouchUpInside];
                [self.bottomView addSubview:button];
                
            }
        } break;
        case 4:
        {
            for (NSInteger i = 1; i <= 2; i++) {
                CGRect frame = CGRectMake(ScreenWidth-(kong+buttonW)*i, buttonY, buttonW, self.bottomView.height-buttonY*2);// self.fourthBackView.width
                
                OrderButtonType type;
                NSString *buttonTitle;
                UIColor *color, *borderColor;
                if (i == 1) {
                    type = OrderButtonTypeDelete;
                    buttonTitle = @"删除订单";
                    color = [UIColor ThemeColor];
                    borderColor = [UIColor ThemeColor];
                } else {
                    type = OrderButtonTypeCheck;
                    buttonTitle = @"查看物流";
                    color = [UIColor blackTextColor];
                    borderColor = [UIColor grayTextColor];
                }
                
                OrderHalfButton *button = [OrderHalfButton orderButtonWithType:type frame:frame buttonTitle:buttonTitle color:color borderColor:borderColor];
                [button addTarget:self action:@selector(orderButtonAction:) forControlEvents:UIControlEventTouchUpInside];
                [self.bottomView addSubview:button];
                
            }
        } break;
        case 5:
        {
            OrderHalfButton *button = [OrderHalfButton orderButtonWithType:OrderButtonTypeDelete frame:CGRectMake(ScreenWidth-(kong+buttonW), buttonY, buttonW, self.bottomView.height-buttonY*2) buttonTitle:@"删除订单" color:[UIColor ThemeColor] borderColor:[UIColor ThemeColor]];
            [button addTarget:self action:@selector(orderButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            [self.bottomView addSubview:button];
        } break;
        case 6:
        {
            OrderHalfButton *button = [OrderHalfButton orderButtonWithType:OrderButtonTypeCheck frame:CGRectMake(ScreenWidth-(kong+buttonW), buttonY, buttonW, self.bottomView.height-buttonY*2) buttonTitle:@"查看物流" color:[UIColor blackTextColor] borderColor:[UIColor grayTextColor]];
            [button addTarget:self action:@selector(orderButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            [self.bottomView addSubview:button];
        } break;
        case 7:
        {
            OrderHalfButton *button = [OrderHalfButton orderButtonWithType:OrderButtonTypeDelete frame:CGRectMake(ScreenWidth-(kong+buttonW), buttonY, buttonW, self.bottomView.height-buttonY*2) buttonTitle:@"删除订单" color:[UIColor ThemeColor] borderColor:[UIColor ThemeColor]];
            [button addTarget:self action:@selector(orderButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            [self.bottomView addSubview:button];
        } break;
        case 8:
        {
            
        } break;
        default:
            break;
    }
}
- (void)refundAction:(OrdersonModel *)goodsModel {
    // 点击“申请退款”按钮时跳转
    OrderModel *tempModel = [OrderModel mj_objectWithKeyValues:self.detailModel];
    [tempModel.ordergoods removeAllObjects];
    [tempModel.ordergoods addObject:goodsModel];
    
    RefundViewController *refundVC = [[RefundViewController alloc] init];
    refundVC.detailModel = tempModel;
    [self.navigationController pushViewController:refundVC animated:YES];
}
- (void)reportAction:(OrdersonModel *)goods {
    // 点击“举报”按钮时跳转
    OrderModel *reportModel = [OrderModel mj_objectWithKeyValues:self.detailModel];
    [reportModel.ordergoods removeAllObjects];
    [reportModel.ordergoods addObject:goods];
    
    ReportViewController *reportVC = [[ReportViewController alloc] init];
    reportVC.detailModel = reportModel;
    [self.navigationController pushViewController:reportVC animated:YES];
}
- (void)copyButtonAction {
    UIPasteboard *pboard = [UIPasteboard generalPasteboard];
    pboard.string = self.detailModel.omlogisticsnumber;
    [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"物流单号已拷贝" animated:YES];
}
- (void)orderButtonAction:(OrderHalfButton *)button {
    switch (button.type) {
        case OrderButtonTypePay:
            [self payAction:self.detailModel];
            break;
        case OrderButtonTypeCancel:
//            [self evaluateAction:self.detailModel];
            [self cancelAction:self.detailModel];
            break;
        case OrderButtonTypeAlert:
            [self alertAction:self.detailModel];
            break;
        case OrderButtonTypeCheck:
            [self checkAction:self.detailModel];
            break;
        case OrderButtonTypeSure:
            [self sureAction:self.detailModel];
            break;
        case OrderButtonTypeDelete:
            [self deleteAction:self.detailModel];
            break;
        case OrderButtonTypeEvaluate:
            [self evaluateAction:self.detailModel];
            break;
        default:
            break;
    }
}

- (void)uploadWechatPay:(NSDictionary *)parameters {
    /*
    if (![WXApi isWXAppInstalled]) {
        [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"没有安装微信" animated:YES];
        return;
    }
    if (![WXApi isWXAppSupportApi]) {
        [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"当前微信版本过低" animated:YES];
        return;
    }
    
    PayReq *request   = [[PayReq alloc] init];
    //request.openID    = responseObject[@"data"][@"appId"];
    request.partnerId = Wechat_partnerId;
    request.prepayId  = parameters[@"prepayid"];
    request.package   = parameters[@"package"];//Sign=WXPay
    request.nonceStr  = parameters[@"noncestr"];
    request.timeStamp = [parameters[@"timestamp"] unsignedIntValue];
    request.sign      = parameters[@"sign"];
    if ([WXApi sendReq:request]) {
        NSLog(@"发送成功");
        
    } else {
        NSLog(@"发送失败");
        [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"订单获取失败" animated:YES];
    }
    */
}

- (void)uploadAlipay:(NSString *)orderString {
    
    __weak typeof(self) weakSelf = self;
    // NOTE: 调用支付结果开始支付
    [[AlipaySDK defaultService] payOrder:orderString fromScheme:AppScheme callback:^(NSDictionary *resultDic) {
        NSLog(@"reslut = %@",resultDic);
        PayStatusViewController *statusVC = [[PayStatusViewController alloc] init];
        statusVC.osid = weakSelf.omid;
        if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
            //成功
            statusVC.type = StatusTypePaySuccess;
        } else {
            //[MBProgressHUD myShowHUDAddedTo:weakSelf.view labelText:@"付款失败" animated:YES];
            statusVC.type = StatusTypePayFail;
        }
        [weakSelf.navigationController pushViewController:statusVC animated:YES];
    }];
    
}

/**
 付款
 */
- (void)uploadPayOrder:(NSString *)payType price:(NSString *)price {
    NSString *payUrl;
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setObject:self.omid forKey:@"omid"];
    if ([payType isEqualToString:@"0"]) {
        payUrl = URL_Pay_Wechat;
    } else if ([payType isEqualToString:@"1"]) {
        payUrl = URL_Pay_Alipay;
    } else {
        payUrl = URL_Pay_Balance;
        [dic setObject:price forKey:@"price"];
    }
    
    __block typeof(self) blockSelf = self;
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:payUrl parameters:dic success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        if ([payType isEqualToString:@"2"]) {
            PayStatusViewController *statusVC = [[PayStatusViewController alloc] init];
            statusVC.osid = blockSelf.omid;
            if ([responseObject[@"code"] isEqualToString:@"200"]) {
                statusVC.type = StatusTypePaySuccess;
            } else {
                statusVC.type = StatusTypePayFail;
            }
            [blockSelf.navigationController pushViewController:statusVC animated:YES];
        } else if ([responseObject[@"code"] isEqualToString:@"200"]) {
            if ([payType isEqualToString:@"1"]) {
                [blockSelf uploadAlipay:responseObject[@"data"]];
            } else if ([payType isEqualToString:@"0"]) {
                [blockSelf uploadWechatPay:responseObject[@"data"]];
            }
        } else {
            [MBProgressHUD showError:blockSelf.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        [MBProgressHUD showError:blockSelf.view title:@"" code:@"" animated:YES];
    }];
}
- (void)payAction:(OrderModel *)model {
    NSLog(@"付款 %@",model.omid);
    [self.payView.priceLabel setHidden:NO];
    [self.payView.priceTF setHidden:YES];
    
    [self.payView.priceLabel setText:[NSString stringWithFormat:@"¥%@",model.omprice]];
    
    self.omid = model.omid;
    [self.payView showView];
    
    __block typeof(self) blockSelf = self;
    self.payView.block = ^(NSString *payType, NSString *rechargeStr) {
        [blockSelf uploadPayOrder:payType price:rechargeStr];
    };
}
/**
 取消订单
 */
- (void)cancelAction:(OrderModel *)model {
    __block typeof(self) blockSelf = self;
    [self showAlertWithTitleArray:@[@"取消",@"确认"] title:@"温馨提示" message:@"确认取消此订单？" alertStyle:UIAlertControllerStyleAlert];
    self.alertBlock = ^(NSString *actionTitle) {
        if ([actionTitle isEqualToString:@"确认"]) {
            NSLog(@"取消订单 %@",model.omid);
            [MBProgressHUD showHUDProgress:blockSelf.view animated:YES];
            [MYAFNetworking POST:URL_Cancel_Order parameters:@{@"omid":model.omid} success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
                [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
                if ([responseObject[@"code"] isEqualToString:@"200"]) {
                    [MBProgressHUD myShowHUDAddedTo:blockSelf.view labelText:@"已取消该订单" animated:YES];
                    if (blockSelf.block) {
                        blockSelf.block(YES);
                    }
                    switch (blockSelf.fromType) {
                        case FromTypeStatus:
                        {
                            [blockSelf popToRootViewController];
                        } break;
                        default:
                        {
                            [blockSelf disMissSelf];
                        } break;
                    }
                } else {
                    [MBProgressHUD showError:blockSelf.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
                [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
                [MBProgressHUD showError:blockSelf.view title:@"" code:@"" animated:YES];
            }];
        }
    };
    
}
/**
 提醒发货
 */
- (void)alertAction:(OrderModel *)model {
    NSLog(@"提醒发货 %@",model.omid);
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:URL_Order_Remind_Shipment parameters:@{@"omid":model.omid} success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"已提醒卖家发货，请耐心等待" animated:YES];
        } else {
            [MBProgressHUD showError:self.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showError:self.view title:@"" code:@"" animated:YES];
    }];
}
/**
 查看物流
 */
- (void)checkAction:(OrderModel *)model {
    NSLog(@"查看物流 %@",model.omid);
    // 点击“查看物流”按钮时跳转
//    LogisticsViewController *logisticsVC = [[LogisticsViewController alloc] init];
//    logisticsVC.orderID = model.omid;
    LogisticsWebViewController *logisticsVC = [[LogisticsWebViewController alloc] init];
    logisticsVC.com = model.lccode;
    logisticsVC.nu = model.omlogisticsnumber;
    [self.navigationController pushViewController:logisticsVC animated:YES];
}
/**
 确认收货
 */
- (void)sureAction:(OrderModel *)model {
    NSLog(@"确认收货 %@",model.omid);
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:URL_Confirm_Receipt parameters:@{@"omid":model.omid} success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            [self getNetData];
        } else {
            [MBProgressHUD showError:self.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showError:self.view title:@"" code:@"" animated:YES];
    }];
}
/**
 删除订单
 */
- (void)deleteAction:(OrderModel *)model {
    __block typeof(self) blockSelf = self;
    [self showAlertWithTitleArray:@[@"取消",@"确定"] title:@"温馨提示" message:@"确认删除此订单？" alertStyle:UIAlertControllerStyleAlert];
    self.alertBlock = ^(NSString *actionTitle) {
        if ([actionTitle isEqualToString:@"确定"]) {
            NSLog(@"删除订单 %@",model.omid);
            [MBProgressHUD showHUDProgress:blockSelf.view animated:YES];
            [MYAFNetworking POST:URL_Delete_Order parameters:@{@"omid":model.omid} success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
                [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
                if ([responseObject[@"code"] isEqualToString:@"200"]) {
                    [MBProgressHUD myShowHUDAddedTo:blockSelf.view labelText:@"已删除该订单" animated:YES];
                    if (blockSelf.block) {
                        blockSelf.block(YES);
                    }
                    switch (blockSelf.fromType) {
                        case FromTypeStatus:
                        {
                            [blockSelf popToRootViewController];
                        } break;
                        default:
                        {
                            [blockSelf disMissSelf];
                        } break;
                    }
                } else {
                    [MBProgressHUD showError:blockSelf.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
                [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
                [MBProgressHUD showError:blockSelf.view title:@"" code:@"" animated:YES];
            }];
        }
    };
}
/**
 评价
 */
- (void)evaluateAction:(OrderModel *)model {
    NSLog(@"评价 %@",model.omid);
    // 点击“评价”按钮时跳转
    EvaluateViewController *evaluateVC = [[EvaluateViewController alloc] init];
    for (OrdersonModel *temp in model.ordergoods) {
        EvaluateModel *model = [[EvaluateModel alloc] init];
        model.orderson_model = temp;
        model.gid = temp.gid;
        model.ogid = temp.ogid;
        model.escore = @"5";
        model.econtent = @"";
        model.eiimgs = @"";
        model.isanonymous = NO;
        
        [evaluateVC.tableArray addObject:model];
    }
    __block typeof(self) blockSelf = self;
    evaluateVC.block = ^(BOOL isEvaluateOrder) {
        if (isEvaluateOrder) {
            if (blockSelf.block) {
                blockSelf.block(YES);
            }
            [blockSelf disMissSelf];
        }
    };
    [self.navigationController pushViewController:evaluateVC animated:YES];
    
}
/**
 修改价格
 */
- (void)changePriceAction:(OrderModel *)model indexPath:(NSIndexPath *)indexPath {
    NSLog(@"修改价格");
    OrderModel *tempModel = [OrderModel mj_objectWithKeyValues:model];
    [tempModel.ordergoods removeAllObjects];
    [tempModel.ordergoods addObject:model.ordergoods[indexPath.row-1]];
//    EditPriceViewController *editPriceVC = [[EditPriceViewController alloc] init];
//    editPriceVC.detailModel = tempModel;
//    __block typeof(self) blockSelf = self;
//    editPriceVC.block = ^(BOOL isEditPrice) {
//        if (isEditPrice) {
//            [blockSelf getNetData];
//        }
//    };
//    [self.navigationController pushViewController:editPriceVC animated:YES];
}
/**
 查看评价
 */
- (void)checkEvaluateAction:(OrdersonModel *)model {
    NSLog(@"查看评价");
//    GoodEvaluateListViewController *goodEvaluateVC = [[GoodEvaluateListViewController alloc] init];
//    goodEvaluateVC.gid = model.gid;
//    [self.navigationController pushViewController:goodEvaluateVC animated:YES];
}
/**
 关闭订单
 */
- (void)closeOrderAction:(OrderModel *)model {
    NSLog(@"关闭订单");
    [self showAlertWithTitleArray:@[@"确认",@"取消"] title:@"温馨提示" message:@"确认要关闭该订单吗？" alertStyle:UIAlertControllerStyleAlert];
    __block typeof(self) blockSelf = self;
    self.alertBlock = ^(NSString *actionTitle) {
        if ([actionTitle isEqualToString:@"确认"]) {
            [MBProgressHUD showHUDProgress:blockSelf.view animated:YES];
            [MYAFNetworking POST:URL_Shop_Close_Order parameters:@{@"omid":model.omid} success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
                [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
                if ([responseObject[@"code"] isEqualToString:@"200"]) {
                    [MBProgressHUD myShowHUDAddedTo:blockSelf.view labelText:@"订单已关闭" animated:YES];
                    if (blockSelf.block) {
                        blockSelf.block(YES);
                    }
                    [blockSelf disMissSelf];
                } else {
                    [MBProgressHUD showError:blockSelf.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
                [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
                [MBProgressHUD showError:blockSelf.view title:@"" code:@"" animated:YES];
            }];
        }
    };
}
/**
 去发货
 */
- (void)sendOutAction:(OrderModel *)model {
    NSLog(@"去发货");
//    EditSendViewController *editSendVC = [[EditSendViewController alloc] init];
//    editSendVC.detailModel = model;
//    __block typeof(self) blockSelf = self;
//    editSendVC.block = ^(BOOL isSend) {
//        if (isSend) {
//            [blockSelf disMissSelf];
//            if (blockSelf.block) {
//                blockSelf.block(YES);
//            }
//        }
//    };
//    [self.navigationController pushViewController:editSendVC animated:YES];
}
/**
 联系买家
 */
- (void)contactBuyer:(OrderModel *)model {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters safeSetObject:model.mid forKey:@"mid"];
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Get_Other_Member_Info parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeObjectForKey:@"code"];
        if ([code isEqualToString:@"200"]) {
            NSDictionary *modelDic = [responseDic safeJsonObjectForKey:@"data"];
            OthersMemberInfoModel *model = [OthersMemberInfoModel mj_objectWithKeyValues:modelDic];
            /*
            // 更新本地融云个人数据
            RCUserInfo *updatedUserInfo =
            [[RCUserInfo alloc] initWithUserId:model.mid name:model.mnickname portrait:model.mimg];
            [[RCIM sharedRCIM] refreshUserInfoCache:updatedUserInfo withUserId:updatedUserInfo.userId];
            
            // 跳转到聊天界面
            ChatViewController *chatVC = [[ChatViewController alloc] init];
            // 会话类型
            chatVC.conversationType = ConversationType_PRIVATE;
            // targetID
            chatVC.targetId = model.mid;
            // title
            chatVC.title = model.mnickname;
            // 多商品，不显示商品链接
            //// 传入商品链接
            //charVC.gid = item.gid;
            //charVC.gname = item.gname;
            [weakSelf.navigationController pushViewController:chatVC animated:YES];
            */
        } else {
            [MBProgressHUD showError:weakSelf.view title:@"" code:code animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        [MBProgressHUD showError:weakSelf.view title:@"" code:@"" animated:YES];
    }];
}
// 哈哈商城
- (void)getCustomerInfo:(OrderModel *)itemModel {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    //    [parameters safeSetObject:itemModel.shop.mid forKey:@"mid"];
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Get_Customer parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeObjectForKey:@"code"];
        if ([code isEqualToString:@"200"]) {
            NSDictionary *data = [responseDic safeJsonObjectForKey:@"data"];
            /*
            CustomerModel *customerModel = [CustomerModel mj_objectWithKeyValues:data];
            // 更新本地融云个人数据
            RCUserInfo *updatedUserInfo =
            [[RCUserInfo alloc] initWithUserId:customerModel.rcid name:customerModel.uname portrait:customerModel.img];
            [[RCIM sharedRCIM]
             refreshUserInfoCache:updatedUserInfo
             withUserId:updatedUserInfo.userId];
            
            // 跳转到聊天界面
            ChatViewController *chatVC = [[ChatViewController alloc] init];
            // 会话类型
            chatVC.conversationType = ConversationType_PRIVATE;
            // targetID
            chatVC.targetId = updatedUserInfo.userId;
            // title
            chatVC.title = updatedUserInfo.name;
            //// 传入商品链接
            //charVC.gid = itemModel.gid;
            //charVC.gname = itemModel.gname;
            [weakSelf.navigationController pushViewController:chatVC animated:YES];
            */
        } else {
            [MBProgressHUD showError:weakSelf.view title:@"" code:code animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        [MBProgressHUD showError:weakSelf.view title:@"" code:@"" animated:YES];
    }];
}
/**
 查看他人店铺
 */
- (void)clickHeaderCheckStore:(OrderModel *)model {
    NSLog(@"查看他人店铺");
    /*
    ShopModel *shopModel = model.shop;
    if (![shopModel.sid isEqualToString:@"0"]) {
//        OthersStoreViewController *otherStoreVC = [[OthersStoreViewController alloc] init];
//        otherStoreVC.mid = shopModel.mid;
//        [self.navigationController pushViewController:otherStoreVC animated:YES];
    }
     */
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//    if ([self.detailModel.omstatus isEqualToString:@"0"] || [self.detailModel.omstatus isEqualToString:@"1"]) {
//        return 2;
//    }
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return 2;
        case 1:
            switch (self.fromType) {
                case FromTypeSelfOrder: case FromTypeStatus:
                    return self.detailModel.ordergoods.count*2;
                case FromTypeMineStore:
                    return self.detailModel.ordergoods.count+3;
                default:
                    return 0;
            }
        case 2:
            return 2;
        default:
            return 0;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    OrderType cellType;
    switch (self.fromType) {
        case FromTypeSelfOrder: case FromTypeStatus:
            cellType = OrderTypeFromSelf;
            break;
        case FromTypeMineStore:
            cellType = OrderTypeFromMineStore;
            break;
        default:
            cellType = OrderTypeNone;
            break;
    }
    OrderDetailTableViewCell *cell = [OrderDetailTableViewCell orderDetailCellWith:tableView indexPath:indexPath count:self.detailModel.ordergoods.count type:cellType];
    [cell updateCellWith:self.detailModel indexPath:indexPath type:cellType];
    cell.detailBlock = ^(DetailCellClickType type) {
        switch (type) {
            case DetailCellClickTypeRefund:
            {
                [self refundAction:self.detailModel.ordergoods[(indexPath.row-1)/2]];
            } break;
            case DetailCellClickTypeReport:
            {
                [self reportAction:self.detailModel.ordergoods[(indexPath.row-1)/2]];
            } break;
            case DetailCellClickTypeCopy:
            {
                [self copyButtonAction];
            } break;
            case DetailCellClickTypeStoreChangePrice:
            {
                [self changePriceAction:self.detailModel indexPath:indexPath];
            } break;
            case DetailCellClickTypeStoreCheckEvaluate:
            {
                [self checkEvaluateAction:self.detailModel.ordergoods[indexPath.row-1]];
            } break;
            case DetailCellClickTypeStoreClose:
            {
                [self closeOrderAction:self.detailModel];
            } break;
            case DetailCellClickTypeStoreSendOut:
            {
                [self sendOutAction:self.detailModel];
            } break;
            case DetailCellClickTypeStoreCheck:
            {
                [self checkAction:self.detailModel];
            } break;
            case DetailCellClickTypeStoreDelete:
            {
                [self deleteAction:self.detailModel];
            } break;
            case DetailCellClickTypeService:
            {
                switch (self.fromType) {
                    case FromTypeSelfOrder: case FromTypeStatus:
                    {
                        if ([self.detailModel.sid isEqualToString:@"0"]) {
                            NSLog(@"联系客服");
                            [self goToServiceChat];
                            break;
                            // 自营
                            [self getCustomerInfo:self.detailModel];
                        } else {
                            // 个人、企业
                            [self contactBuyer:self.detailModel];
                        }
                    } break;
                    case FromTypeMineStore:
                    {
                        NSLog(@"联系买家");
                        [self contactBuyer:self.detailModel];
                    } break;
                    default:
                        break;
                }
            } break;
            default:
                break;
        }
    };
    return cell;
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    if (indexPath.section == 1 && indexPath.row == 0) {
//        [self clickHeaderCheckStore:self.detailModel];
//        return;
//    }
    if (indexPath.section == 1) {
        switch (self.fromType) {
            case FromTypeSelfOrder: case FromTypeStatus:
            {
                if (indexPath.row%2 == 0) {
                    NSLog(@"跳转商品详情");
                    //MARK:测试 跳转商品详情
                    OrdersonModel *model = self.detailModel.ordergoods[indexPath.row/2];
                    if (!model.isshelves) {
                        [MBProgressHUD showError:self.view title:@"该商品已下架" code:@"" animated:YES];
                        return;
                    }
                    GoodsDetailViewController *goodVC = [[GoodsDetailViewController alloc] init];
                    goodVC.gid = model.gid;
                    [self.navigationController pushViewController:goodVC animated:YES];
                }
            } break;
            case FromTypeMineStore:
            {
                if (indexPath.row < self.detailModel.ordergoods.count+1) {
                    NSLog(@"跳转商品详情");
//                    //MARK:测试 跳转商品详情
//                    OrdersonModel *model = self.detailModel.goods[indexPath.row];
//                    GoodDetailViewController *goodVC = [[GoodDetailViewController alloc] init];
//                    goodVC.gid = model.gid;
//                    [self.navigationController pushViewController:goodVC animated:YES];
                }
            } break;
            default:
                break;
        }
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case 0:
        {
            switch (indexPath.row) {
                case 0:
                    return 70.0;
                case 1:
                    return 80.0;
                default:
                    return 0;
            }
        } break;
        case 1:
        {
            switch (self.fromType) {
                case FromTypeSelfOrder: case FromTypeStatus:
                {
                    if (indexPath.row%2 == 0) {
                        return 112.0;
                    } else if (indexPath.row%2 == 1) {
                        switch (self.detailModel.omstatus.integerValue) {
                            case 1: case 2: case 3:
                                return 42.0;
                            default:
                                return 0;
                        }
                    }
                    return 0;
                } break;
                case FromTypeMineStore:
                {
                    if (indexPath.row == self.detailModel.ordergoods.count+1) {
                        return 42;
                    } else if (indexPath.row == self.detailModel.ordergoods.count+2 || indexPath.row == 0) {
                        return 44.0;
                    } else {
                        if ([self.detailModel.omstatus isEqualToString:@"0"] || [self.detailModel.omstatus isEqualToString:@"4"]) {
                            // 状态0已提交，1已付款，2已发货，3已签收，4已评价，5已取消，6已删除，7退款申请，8已退款(7,8不会返)
                            return 144;
                        }
                        return 100.0;
                    }
                } break;
                default:
                    return 0;
            }
        } break;
        case 2:
            switch (indexPath.row) {
                case 0:
                    return UITableViewAutomaticDimension;
                case 1:
                    return 44.0;
                default:
                    return 0;
            }
        default:
            return 0;
    }
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case 0:
        {
            switch (indexPath.row) {
                case 0:
                    return 70.0;
                case 1:
                    return 80.0;
                default:
                    return 0;
            }
        } break;
        case 1:
        {
            switch (self.fromType) {
                case FromTypeSelfOrder: case FromTypeStatus:
                {
                    if (indexPath.row%2 == 0) {
                        return 112.0;
                    } else if (indexPath.row%2 == 1) {
                        switch (self.detailModel.omstatus.integerValue) {
                            case 1: case 2: case 3:
                                return 42.0;
                            default:
                                return 0;
                        }
                    }
                    return 0;
                } break;
                case FromTypeMineStore:
                {
                    if (indexPath.row == self.detailModel.ordergoods.count+1) {
                        return 42;
                    } else if (indexPath.row == self.detailModel.ordergoods.count+2 || indexPath.row == 0) {
                        return 44.0;
                    } else {
                        if ([self.detailModel.omstatus isEqualToString:@"0"] || [self.detailModel.omstatus isEqualToString:@"4"]) {
                            // 状态0已提交，1已付款，2已发货，3已签收，4已评价，5已取消，6已删除，7退款申请，8已退款(7,8不会返)
                            return 144;
                        }
                        return 100.0;
                    }
                } break;
                default:
                    return 0;
            }
        } break;
        case 2:
            switch (indexPath.row) {
                case 0:
                    return 60.0;
                case 1:
                    return 44.0;
                default:
                    return 0;
            }
        default:
            return 0;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 2) {
        return 0;
    }
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 10)];
    [view setBackgroundColor:[UIColor clearColor]];
    return view;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
